﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using Aspfm.Dal;
using Aspfm.Main;

namespace Aspfm.Html
{
    public class AspfmHtml
    {
        const string ext = ".data";
        public const string pageext = ".aspx";
        const string dirtemp = "temp.aspfm.data";

        public static void CreateHtml(string filename)
        {
            if (System.IO.File.Exists(filename))
            {
                DateTime Aspfmdate = System.IO.File.GetCreationTime(filename);
                DateTime Aspfmupdatedate = System.IO.File.GetLastWriteTime(filename);
                if (Aspfmdate != Aspfmupdatedate)
                {
                    Aspfmdate = Aspfmupdatedate;
                    System.IO.File.SetCreationTime(filename, Aspfmupdatedate);
                }
                bool isNewCreate=true;
                string datafile = GetDataFile(filename);
                string pagefile=Path.GetDirectoryName(filename) +"\\"+ Path.GetFileNameWithoutExtension(filename) + pageext;
                if (System.IO.File.Exists(datafile) &&
                    System.IO.File.Exists(pagefile))
                {
                    DateTime AspfmDatadate = System.IO.File.GetCreationTime(datafile);
                    //DateTime AspfmPagedate = System.IO.File.GetCreationTime(pagefile);
                    DateTime uAspfmDatadate = System.IO.File.GetLastWriteTime(datafile);
                    //DateTime uAspfmPagedate = System.IO.File.GetLastWriteTime(pagefile);
                    //int bp=DateTime.Compare(Aspfmdate, AspfmPagedate);
                    //int bd=DateTime.Compare(Aspfmdate, AspfmDatadate);
                    //if ( bp< 0 && bd < 0)
                    //{
                    //    isNewCreate = false;
                    //}
                    if (//DateTime.Compare(Aspfmdate, AspfmPagedate.AddSeconds(-1)) == 0 &&
                       DateTime.Compare(Aspfmdate, AspfmDatadate.AddSeconds(-1)) == 0 &&
                        DateTime.Compare(Aspfmdate, uAspfmDatadate.AddSeconds(-1)) == 0 
                    //&& DateTime.Compare(Aspfmdate, uAspfmPagedate.AddSeconds(-1)) == 0
                    )
                    {
                        isNewCreate = false;
                    }
                }
                if (isNewCreate)
                {
                    //System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
                    //sw.Start();
                    string temppath = System.IO.Path.GetTempPath() + Path.GetFileName(filename);
                    if (string.IsNullOrEmpty(ZipHelper.unZipFile(filename, Path.GetDirectoryName(temppath), Aspfm.Main.BaseAshx.Extension, true)))
                    {
                        FileStream fileStream = new FileStream(temppath, FileMode.Open, FileAccess.Read, FileShare.Read);
                        BinaryFormatter b = new BinaryFormatter();
                        AspfmAll AspfmAll = b.Deserialize(fileStream) as AspfmAll;
                        fileStream.Close();
                        File.Delete(temppath);
                        //sw.Stop();

                        if (File.Exists(datafile))
                        {
                            File.Delete(datafile);
                        }
                        if (!Directory.Exists(Path.GetDirectoryName(datafile)))
                        {
                            Directory.CreateDirectory(Path.GetDirectoryName(datafile));
                        }
                        //System.Diagnostics.Stopwatch sw1 = new System.Diagnostics.Stopwatch();
                        //sw1.Start();
                        FileStream fileStream1 = new FileStream(datafile, FileMode.Create);
                        BinaryFormatter b1 = new BinaryFormatter();
                        b.Serialize(fileStream1, AspfmAll.MyDataSql);
                        fileStream1.Close();
                        //sw1.Stop();
                        AspfmCreate bcreate = new AspfmCreate();
                        bcreate.CreateHtml(AspfmAll, pagefile);


                        System.IO.File.SetCreationTime(datafile, Aspfmdate.AddSeconds(1));
                        System.IO.File.SetCreationTime(pagefile, Aspfmdate.AddSeconds(1));
                        System.IO.File.SetLastWriteTime(datafile, Aspfmdate.AddSeconds(1));
                        System.IO.File.SetLastWriteTime(pagefile, Aspfmdate.AddSeconds(1));
                    }
                }
            }
        }
        public static string GetDataFile(string AspfmFile)
        {
            if (System.IO.File.Exists(AspfmFile))
            {
                string datafile = Path.GetDirectoryName(AspfmFile) + "\\" + dirtemp + "\\" + Path.GetFileName(AspfmFile) + ext;

                return datafile;
            }
            return "";
        }

        public static List<AspfmDataSource> GetAspfmData(string AspfmFile)
        {
            if (System.IO.File.Exists(AspfmFile))
            {
                CreateHtml(AspfmFile);
                string datafile = GetDataFile(AspfmFile);
                if (System.IO.File.Exists(datafile))
                {
                    object Aspfmdataobj = CacheHelper.GetCache("Aspfm." + datafile);
                    if (Aspfmdataobj != null && Aspfmdataobj is List<AspfmDataSource>)
                     {
                        List<AspfmDataSource> Aspfmdata = (List<AspfmDataSource>)Aspfmdataobj;
                        List<AspfmDataSource> Aspfmdatanew = new List<AspfmDataSource>();
                        foreach (AspfmDataSource asds in Aspfmdata)
                        {
                            Aspfmdatanew.Add(asds.Copy());
                        }
                        return Aspfmdatanew;
                     }
                     else
                     {
                         //System.Diagnostics.Stopwatch sw2 = new System.Diagnostics.Stopwatch();
                         //sw2.Start();
                         FileStream fileStream2 = new FileStream(datafile, FileMode.Open, FileAccess.Read, FileShare.Read);
                         BinaryFormatter b2 = new BinaryFormatter();
                         List<AspfmDataSource> Aspfmdata = b2.Deserialize(fileStream2) as List<AspfmDataSource>;
                         fileStream2.Close();

                         CacheHelper.SetCache("Aspfm." + datafile, Aspfmdata, datafile);
                         //sw2.Stop();
                         return Aspfmdata;
                     }
                }
            }
            return null;
        }

        public static void CheckAspfm()
        {
            if (System.Web.HttpContext.Current != null)
            {
                string ext = System.IO.Path.GetExtension(System.Web.HttpContext.Current.Request.Url.LocalPath).ToLower();
                if (ext == "" || ext == BaseAshx.Extension || ext == pageext)
                {
                    string tempLocalPath = System.IO.Path.GetDirectoryName(System.Web.HttpContext.Current.Request.Url.LocalPath)+"\\" + System.IO.Path.GetFileNameWithoutExtension(System.Web.HttpContext.Current.Request.Url.LocalPath);
                    string Aspfmfile = BaseAshx.CurrentPath() + tempLocalPath;
                    if (System.IO.File.Exists(Aspfmfile + BaseAshx.Extension))
                    {
                        CreateHtml(Aspfmfile + BaseAshx.Extension);
                        if (ext != pageext)
                        {
                           // System.Web.HttpContext.Current.RewritePath(System.Web.HttpContext.Current.Request.Url.LocalPath + pageext, "pathinfo", System.Web.HttpContext.Current.Request.Url.Query.TrimStart('?'));

                            System.Web.HttpContext.Current.RewritePath(tempLocalPath + pageext + System.Web.HttpContext.Current.Request.Url.Query);

                            //string url = System.Web.HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) +
                            //    System.Web.HttpContext.Current.Request.Url.LocalPath.Substring(0, System.Web.HttpContext.Current.Request.Url.LocalPath.Length -
                            //    ext.Length) + pageext + System.Web.HttpContext.Current.Request.Url.Query;
                            //System.Web.HttpContext.Current.Response.Redirect(url, false);
                            //System.Web.HttpContext.Current.Response.End();
                            /*当您在页处理程序中使用此方法终止一个页面的请求并启动另一页面的请求时，请将 endResponse 设置为 false 然后调用 CompleteRequest() 方法。 
                             * 如果指定 endResponse 参数的 true，则该方法调用原始请求的 End 方法。此方法完成时引发 ThreadAbortException 异常。
                             * 此异常有不利的影响（对 Web 应用程序的性能），这就是为什么建议传递 false（针对 endResponse 参数）
                             */
                        }
                    }
                }
            }
        }
    }
}
